package com.example.win.android_banduyujia.peopleactivity.activity.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Window;
import android.widget.Toast;

import com.example.win.android_banduyujia.R;
import com.example.win.android_banduyujia.entity.Constants;
import com.example.win.android_banduyujia.peopleactivity.ui.activity.BaseActivity;

import java.io.File;

/**
 * Created by Win on 2015/8/18.
 */
public class ImageFetchActivity extends BaseActivity {
    public static final  String ACTION_TYPE = " com.example.win.android_banduyujia.activity.ImageFetchActivity.ACTION_TYPE";

    public static final int REQUEST_CODE_CAMERA = 0X000;
    public static final int REQUEST_CODE_ALBUM = 0X001;
    public final static int ACTION_TYPE_CROP = 0x003;
    public final static int ACTION_TYPE_FINISH = 0x004;
    private int mActionType = 0;
    private String   mPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_image_fetch);
        mActionType = getIntent().getIntExtra(ACTION_TYPE, REQUEST_CODE_CAMERA);
        // mPath = Constants.IMAGE_CAMERA_URI.getPath();
        switch (mActionType){
            case REQUEST_CODE_CAMERA: // 相机
                 gotoCameraActivity();
                break;
            case  REQUEST_CODE_ALBUM: // 相册
                 gotoPicturePickActivity();
                break;
        }
    }

    private void gotoCameraActivity() {
         startCameraActivity(ACTION_TYPE_CROP);
         mActionType = ACTION_TYPE_CROP;
    }

    private void gotoPicturePickActivity() {
        startPictureActivity(REQUEST_CODE_ALBUM);
        mActionType = ACTION_TYPE_CROP;
    }

    // 启动选择图片的activity
    public void startPictureActivity(int requestCode){
        Intent  intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, requestCode);
    }

    // 启动选择相机的activity
    public void startCameraActivity(int requestCode){
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
       if(hasSdcard()){
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
      }
        startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == PHOTO_REQUEST_GALLERY){
            if(data != null){
                String  fileRealPath;
                // 得到图片的全路径
                Uri  uri = data.getData();
                crop(uri);
                if(uri != null){
                    String  imgUriPath = uri.getPath();
                    Cursor  cursor = getContentResolver().query(data.getData(), null, null, null,null);
                    if(cursor != null && cursor.moveToFirst()){
                        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        fileRealPath = cursor.getString(columnIndex);
                    }else{
                        fileRealPath = imgUriPath;
                    }
                }else{
                    fileRealPath = Constants.IMAGE_CAPTURE_URI.getPath();
                }
                mPath = fileRealPath;
            }
        }else if(requestCode == PHOTO_REQUEST_CAMERA){
            if(hasSdcard()){
                tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
                crop(Uri.fromFile(tempFile));
           }else{
                Toast.makeText(getApplicationContext(), "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG).show();
            }
        }else if(requestCode == PHOTO_REQUEST_CUT){
            try{
               bitmap = data.getParcelableExtra("data");
                //mImageHeaderView.setImageBitmap(bitmap);
                boolean  delete = tempFile.delete();
                System.out.println("delete = " + delete);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            finishActivity(true);
        }
    }

    private void finishActivity(boolean isOk) {
        if(isOk){
            Intent intent = new Intent();
            intent.setData(Constants.IMAGE_CAPTURE_URI);
            setResult(RESULT_OK, intent);
            finish();
        }else{
            setResult(RESULT_CANCELED);
            finish();
        }
    }

    // 剪切图片
    private void crop(Uri uri) {
       // 裁剪图片意图
        Intent  intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX",250);
        intent.putExtra("outputY",250);
        // 图片格式
        intent.putExtra("outputFormat","JPEG");
        intent.putExtra("noFaceDection", true); // 取消人脸识别
        intent.putExtra("return-data", true); // true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private boolean hasSdcard() {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        }else{
            return false;
        }
    }

    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    /* 头像名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private File tempFile;

    private Bitmap bitmap;
}
